package com.ybwh.springboot2.common.mybatis.plugin.sass;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.HashSet;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;

@Slf4j
@Intercepts({
        @Signature(type = Executor.class, method = "query",
                args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "query",
                args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),})
public abstract class AbstractSassInterceptor implements Interceptor {

    protected final static Set<String> IGNORE_TABLES = new HashSet<>();

    /**
     * @param ignoreTables 忽略的表,多个表用逗号隔开
     */
    public AbstractSassInterceptor(String ignoreTables) {
        if (StringUtils.isBlank(ignoreTables)) {
            return;
        }

        for (String t : ignoreTables.split(",")) {
            IGNORE_TABLES.add(t);
        }
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {


        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameterObject = args[1];
        String tenantId = getTenantId((MapperMethod.ParamMap) parameterObject, ms);


        BoundSql boundSql = ms.getBoundSql(parameterObject);
        String sql = boundSql.getSql();


        String newSql = reWriteSql(sql, tenantId);
        log.info("--------sql:{}", newSql);
        log.info("--------param:{}", parameterObject);


        BoundSql bs = new BoundSql(ms.getConfiguration(), newSql, boundSql.getParameterMappings(), parameterObject);

        MappedStatement newMs = copyFromMappedStatement(ms, new BoundSqlSqlSource(bs));
        for (ParameterMapping mapping : boundSql.getParameterMappings()) {
            String prop = mapping.getProperty();
            if (boundSql.hasAdditionalParameter(prop)) {
                bs.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
            }
        }
        args[0] = newMs;

        return invocation.proceed();
    }


    protected String getTenantId(MapperMethod.ParamMap parameterObject, MappedStatement mappedStatement) throws ClassNotFoundException {

        // 优先使用参数传进来的 租户ID,其次线程中的租户ID


        // 反射去拿参数位置
        String namespace = mappedStatement.getId();
        String className = namespace.substring(0, namespace.lastIndexOf("."));
        String mName = mappedStatement.getId().substring(mappedStatement.getId().lastIndexOf(".") + 1, mappedStatement.getId().length());
        Method[] ms = Class.forName(className).getMethods();


        SassTenantId sassTenantId = null;
        for (Method m : ms) {
            if (!Objects.equals(mName, m.getName())) {
                continue;
            }

            if (parameterObject == null) {
                //没有参数列表
                return TenantIdHelper.getTenantId();
            }


            for (int i = 0, len = m.getParameters().length; i < len; i++) {
                Parameter p = m.getParameters()[i];
                sassTenantId = p.getAnnotation(SassTenantId.class);
                if (null == sassTenantId) {
                    continue;
                }

                Object paramValue = parameterObject.get("param" + (i + 1));
                return paramValue.toString();

            }

            if (null == sassTenantId) {
                //没有指定SassTenantId
                return TenantIdHelper.getTenantId();
            }
        }


        return null;
    }

    protected abstract String reWriteSql(String sql, String tenantId);

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
    }


    protected MappedStatement copyFromMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
        MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if (ms.getKeyProperties() != null && ms.getKeyProperties().length > 0) {
            builder.keyProperty(ms.getKeyProperties()[0]);
        }
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        builder.resultMaps(ms.getResultMaps());
        builder.resultSetType(ms.getResultSetType());
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());
        return builder.build();
    }

    public static class BoundSqlSqlSource implements SqlSource {
        protected BoundSql boundSql;

        public BoundSqlSqlSource(BoundSql boundSql) {
            this.boundSql = boundSql;
        }

        public BoundSql getBoundSql(Object parameterObject) {
            return boundSql;
        }
    }

}